<template>
<view class="container"> 
  <form class="info_Form" @submit="changeUserInfo">
    <view class="info_image_container">
      <image :src="loginUser.platformUser.headimgurl||'https://image1.sansancloud.com/zhihuishangwu/2019_12/5/11/8/56_403.jpg?x-oss-process=style/preview_120'" mode="aspectFill" @tap="changeImage"></image><!--  bindtap='changeImage' -->
    </view>
    <view class="inputGroup" catchsubmit="changeUserInfo" v-if="!sendOptionData&&!showAddressForm">
      

      <view class="input_item_container">
        <view class="input_item_container_title">昵称</view>
        <input placeholder="用户昵称" maxlength="20" name="nickname" :value="loginUser.platformUser.nickName"></input>
      </view>
      
      <view class="input_item_container">
        <view class="input_item_container_title">手机号码</view>
        <input placeholder="手机号码" maxlength="15" name="telno" :value="loginUser.platformUser.telno"></input>
      </view>
      <view class="input_item_container">
        <view class="input_item_container_title">个性签名</view>
        <input placeholder="个性签名" maxlength="20" name="userTip" :value="loginUser.platformUser.userTip"></input>
      </view>
    </view> 
    <view class="CheckBox" v-if="!sendOptionData&&!showAddressForm">
      <view class="checkBox_container">
        <view class="checkBoxName">性别</view>
        <radio-group name="sex" @change="sexChange">
          <!-- <radio name="sex1" value='1' color='{{setting.platformSetting.defaultColor}}' checked='{{loginUser.sex}}'>男</radio>
          <radio name="sex1" value='0' color='{{setting.platformSetting.defaultColor}}' checked='{{loginUser.sex}}'>女</radio> -->
          <radio name="sex1" value="1" :color="setting.platformSetting.defaultColor" :checked="loginUser.platformUser.sex == 1">男</radio>
          <radio name="sex1" value="2" :color="setting.platformSetting.defaultColor" :checked="!loginUser.platformUser.sex || loginUser.platformUser.sex ==2">女</radio>

        </radio-group>
      </view>
    </view>
<!-- 用户表单 -->
    <form-detail-component id="userForm" :receiveData="sendOptionData" showTitle="false" showBtn="false" :userAddressCustomFormCommitId="userInfoFormCommitId" v-if="sendOptionData&&showAddressForm" @sendDataFun="getDataFun"></form-detail-component>
    <button :loading="butn_show_loading" class="signIn" formType="submit" :style="'color:#fff;background:' + setting.platformSetting.defaultColor">保存用户资料</button>
     <!-- <button class='signIn'  bindtap='bindgetuserinfo' 
    style='color:{{setting.platformSetting.defaultColor}};background:#fff;border:1px solid {{setting.platformSetting.defaultColor}}'>同步微信资料</button>  -->
    <!--  #ifdef APP-PLUS -->
    <button class='login_out' v-if="showToIndexState" @tap='toIndexFun' :style='"color:"+setting.platformSetting.defaultColor+";border:1px solid "+setting.platformSetting.defaultColor'>跳过去首页</button>
    <!-- <button class='login_out' @tap='loginOut' :style='"color:"+setting.platformSetting.defaultColor+";border:1px solid "+setting.platformSetting.defaultColor'>退出登录</button> -->
    <!--  #endif -->
    <!--  #ifdef MP-WEIXIN -->
    <!-- <button class='login_out' v-if="showToIndexState" @tap='toIndexFun' :style='"color:"+setting.platformSetting.defaultColor+";border:1px solid "+setting.platformSetting.defaultColor'>跳过去首页</button> -->
    <!--  #endif -->
  </form>
</view>
</template>

<script>

export default {
  data() {
    return {
      loginUser: null,
      butn_show_loading: false,
      hasNoScope: false,
      canIUse: wx.canIUse('button.open-type.getUserInfo'),
      sendOptionData: null,
      showAddressForm: false,
      userInfoFormCommitId: '',
      showToIndexState:false,
      userInfo: {
        telno: '',
        headimg: '',
        nickname: '',
        userTip: ''
      },
      setting: "",
      hasUserInfo: false,
      backUrl:'',
    };
  },
  props: {},

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this;
    console.log("=========app.setting===========", getApp().globalData.setting,options);
    this.setData({
      loginUser: getApp().globalData.loginUser,
      hasNoScope: getApp().globalData.hasNoScope,
      setting: getApp().globalData.setting
    });
    if (options.type=='formLogin') {
        if(options.url){
            that.setData({backUrl:options.url})
        }
        that.showToIndexState=true
        that.setData({showToIndexState:that.showToIndexState})
    }
    if (this.canIUse) {
      getApp().globalData.userInfoReadyCallback = res => {
        console.log(res);
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        });
      };
    }

    if (getApp().globalData.setting.platformSetting.userInfoCustomFormId) {
      console.log("有设置用户表单", getApp().globalData.setting.platformSetting.userInfoCustomFormId);
      that.setData({
        showAddressForm: true,
        sendOptionData: {
          customFormId: getApp().globalData.setting.platformSetting.userInfoCustomFormId
        }
      });
    } else {
      that.setData({
        sendOptionData: {}
      });
    }

    if (getApp().globalData.loginUser.platformUser.userInfoFormCommitId) {
      console.log("有提交的内容");
      that.setData({
        userInfoFormCommitId: getApp().globalData.loginUser.platformUser.userInfoFormCommitId
      });
    } else {
      console.log("没有提交的内容"); // that.setData({ userInfoFormCommitId: 2244 })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    if (!getApp().globalData.checkIfLogin()) {
      return;
    }

    console.log(".............");
    console.log(this.loginUser);
    this.imageUrl = this.loginUser.userIcon;
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {},
  methods: {
    toIndexFun:function(){
        let that=this;
        getApp().globalData.toIndex('')
    },
    bindgetuserinfo(e) {
      let that = this;
      wx.getUserInfo({
        success: function (res) {
          console.warn('--获取用户信息--');
          console.log(res.userInfo);
          let userInfo = res.userInfo;
          let loginUser = that.loginUser;
          loginUser.nickName = userInfo.nickName;
          loginUser.platformUser.headimgurl = userInfo.avatarUrl;
          that.imageUrl = userInfo.avatarUrl;
          that.setData({
            loginUser: loginUser
          });
        },
        fail: function (e) {
          console.log(e);
          wx.showModal({
            title: '授权提示',
            content: '取消用户授权可能导致部分功能不可用，请确认授权！',
            cancelText: '拒绝',
            confirmText: '去授权',
            success: function (res) {
              if (res.confirm) {
                wx.openSetting({
                  success: res => {
                    res.authSetting = {
                      "scope.userInfo": true
                    };
                    that.bindgetuserinfo();
                  }
                });
              } else if (res.cancel) {}
            }
          });
        }
      });
    },

    /* 图片 */
    changeImage: function () {
      var that = this;
      wx.chooseImage({
        count: 1,
        // 默认9
        sizeType: ['original', 'compressed'],
        // 可以指定是原图还是压缩图，默认二者都有
        sourceType: ['album', 'camera'],
        // 可以指定来源是相册还是相机，默认二者都有
        success: function (res) {
          // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
          var tempFilePaths = res.tempFilePaths[0];
          let imageParam = {};
          imageParam.imageUrl = tempFilePaths; 
          var customIndex = getApp().globalData.AddClientUrl("/file_uploading.html", imageParam, 'POST');
          wx.uploadFile({
            url: customIndex.url,
            filePath: tempFilePaths,
            name: 'file',
            formData: customIndex.params,
            success: function (res) {
              var data = JSON.parse(res.data);
              console.log(data);
              that.imageUrl = data.relateObj.imageUrl; //do something
              that.userInfo.headimg = that.imageUrl;
              that.toChangeUserInfo(that.userInfo)
            },
            fail: function (res) {
              console.log(res);
            }
          });
          console.log(tempFilePaths); //console.log(that.data.loginUser)
        }
      });
    },
    getDataFun: function (e) {
      let that = this;
      console.log("===getDataFun===", e, e.detail.formId);
      that.userInfo.userInfoFormCommitId = e.detail.formId;
      let params = {
        userInfoFormCommitId: e.detail.formId,
        headimg: that.imageUrl
      };
      getApp().globalData.loginUser.platformUser.userInfoFormCommitId=e.detail.formId
      // that.toChangeUserInfo(params);
      setTimeout(function(){
        if(that.backUrl){
            getApp().globalData.linkEvent(that.backUrl,'reLaunch');
        }else{
            getApp().globalData.toIndex()
        }
      },1000)
    },
    sexChange: function (e) {
      console.log("=====sexChange=====", e);
    },

    /* 提交 */
    //提交成功，重新登陆
    changeUserInfo: function (e) {
      let that = this;
      console.log(e.detail);
      var reLoginData = {
        username: "",
        passworld: ""
      };
      that.setData({
        butn_show_loading: true
      });
      that.userInfo = e.detail.value;
      let phoneNo = that.userInfo.telno;
      that.userInfo.headimg = that.imageUrl;
      that.selectComponent("#userForm").formSubmit();
      // if (!getApp().globalData.setting.platformSetting.userInfoCustomFormId) {
      //   if (!phoneNo || phoneNo.length != 11) {
      //     wx.showToast({
      //       title: "号码格式错误",
      //       image: '/wxcomponents/images/icons/tip.png',
      //       duration: 2000
      //     });
      //     this.setData({
      //       butn_show_loading: false
      //     });
      //     return;
      //   }

      //   that.toChangeUserInfo(this.userInfo);
      // } else {
      //   that.selectComponent("#userForm").formSubmit();
      // }
    },
    toChangeUserInfo: function (userInfo) {
      let that = this;
      let params={headimgurl:userInfo.headimg||that.loginUser.platformUser.headimgurl}
      var customIndex = getApp().globalData.AddClientUrl("/change_user_headimg.html", params, 'post');
      wx.request({
        url: customIndex.url,
        data: customIndex.params,
        header: getApp().globalData.headerPost,
        method: 'POST',
        success: function (res) {
          console.log(res.data);
          if (res.data.errcode == '0') {
            getApp().globalData.loginUser.platformUser.headimgurl=userInfo.headimg
            that.loginUser.platformUser.headimgurl = userInfo.headimg
            that.setData({
              loginUser: that.loginUser
            });
            wx.showToast({
              title: '修改成功',
              icon: 'success',
              duration: 1000
            });
            // setTimeout(function(){
            //   if(that.backUrl){
            //       getApp().globalData.linkEvent(that.backUrl,'reLaunch');
            //   }else{
            //       getApp().globalData.toIndex()
            //   }
            // },1000)
          }else{
                wx.showToast({
                  title: '修改失败',
                  image: '/wxcomponents/images/icons/tip.png',
                  duration: 1000
                });
          }

          that.loginIn();
        },
        fail: function (res) {
          getApp().globalData.loadFail();
        },
        complete: function () {
          that.setData({
            butn_show_loading: false
          });
        }
      });
    },

    /* 退出登录 */
    loginOut: function () {
      getApp().globalData.showToastLoading('loading', true);
      getApp().globalData.loginOut("/logout.html")
    },
    loginIn: function (data) {
      //app.wxLogin()
      getApp().globalData.get_session_userinfo(); // setTimeout(function () { wx.navigateBack() },200)
    },
    setData: function (obj) {
      let that = this;
      let keys = [];
      let val, data;
      Object.keys(obj).forEach(function (key) {
        keys = key.split('.');
        val = obj[key];
        data = that.$data;
        keys.forEach(function (key2, index) {
          if (index + 1 == keys.length) {
            that.$set(data, key2, val);
          } else {
            if (!data[key2]) {
              that.$set(data, key2, {});
            }
          }

          data = data[key2];
        });
      });
    }
  }
};
</script>
<style>
@import "./index.css";
</style>